package server;

import pojo.Host;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    Map<String,Map<String,Map<String,HttpServlet>>> hostMap;
    private String webappsPath;

    public RequestProcessor(Socket socket, Map<String,Map<String,Map<String,HttpServlet>>> hostMap, String webappsPath) {
        this.socket = socket;
        this.hostMap = hostMap;
        this.webappsPath=webappsPath;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            //得到项目map
            Map<String, Map<String, HttpServlet>> contexts = hostMap.get(request.getHost());

            //获取wrapper
            String webName = request.getUrl().split("/")[1];
            Map<String,HttpServlet> wrappers =contexts .get(webName);

            //获取Servlet
            String[] split = request.getUrl().split("/");
            String servletName=split[split.length-1];
            HttpServlet httpServlet = wrappers.get("/"+servletName);

            // 静态资源处理
            if(httpServlet == null) {
                response.outputHtml(request.getUrl(),webappsPath);
            }else{
                // 动态资源servlet请求
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
